package cn.shop.dys.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import c.b.BP;
import c.b.PListener;
import cn.shop.dys.R;
import cn.shop.dys.bean.AddressInfo;
import cn.shop.dys.bean.CheckoutResp;
import cn.shop.dys.bean.CommitOrderRequset;
import cn.shop.dys.bean.OrderInfo;
import cn.shop.dys.bean.PayCenterItem;
import cn.shop.dys.bean.ProductList;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.util.SPUtil;
import cn.shop.dys.widget.ExpandableRelativeLayout;
import cn.shop.lib_common.CommonUtil;

public class PayCenterActivity extends AppCompatActivity {

    private static final int SUCCESS = 0;
    private List<PayCenterItem> mList;
    private static Handler handler = new Handler();
    private ScrollView mScrollView;
    private DrawerLayout mDrawerLayout;
    private LinearLayout mDrawerLayoutRight;
    private TextView tvInvoice;
    private RadioGroup rgInvoiceType;
    private RadioGroup rgInvoiceTitle;
    private RadioGroup rgInvoiceMaterial;
    private RadioGroup rgInvoiceContent;
    private EditText etInvoiceTitle;
    private RelativeLayout rlAddressInfo;
    private LinearLayout productList;
    private LinearLayout checkoutProm;
    private RelativeLayout invoice;
    private RelativeLayout deliveryList;
    private RelativeLayout paymentList;
    private TextView tvAddressInfoName;
    private TextView tvAddressPhoneNumber;
    private ImageView ivAddressInfoAddress;
    private TextView tvAddressInfoAddress;
    private ImageView ivProductListPic;
    private TextView tvProductListName;
    private TextView tvProductListPrice;
    private TextView tvProductListProdNum;
    private TextView tvCheckoutAddupTotalPoint;
    private TextView tvCheckoutAddupTotalCount;
    private TextView tvCheckoutAddupFreight;
    private TextView tvCheckoutAddupProdNum;
    private TextView tvDeliveryList;
    private TextView tvPaymentList;
    private RelativeLayout checkoutAddup;
    private TextView tvCheckoutPromContent;
    private RadioGroup rgDeliveryList;
    private RadioGroup rgPaymentList;
    private ExpandableRelativeLayout deliveryListExpandLayout;
    private ExpandableRelativeLayout paymentListExpandLayout;
//    private ExpandableRelativeLayout addressInfoExpandLayout;
//    private RadioGroup rgAddressInfo;
    private CheckoutResp checkoutResp;
    private AddressInfo[] addressLists;
    private PopupWindow popupWindow;
    private CommitOrderRequset mOrder;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_center);

        mOrder = new CommitOrderRequset();
        initData();
        initToolbar();
        initView();
        //initAddressInfo();

    }



    private void initAddressInfo() {
        // TODO: 2016/4/23 从集合中获取数据，增加子布局
        tvAddressInfoName.setText("姓名:"+checkoutResp.addressInfo.getName());
        tvAddressPhoneNumber.setText(checkoutResp.addressInfo.getPhoneNumber());
        String address = checkoutResp.addressInfo.getProvince()+checkoutResp.addressInfo.getCity()
                +checkoutResp.addressInfo.getAddressArea()+checkoutResp.addressInfo.getAddressDetail();
        tvAddressInfoAddress.setText(address);

        rlAddressInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                addressInfoExpandLayout.toggle();
                popupWindow.showAsDropDown(rlAddressInfo);
            }
        });
//        rgAddressInfo.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                RadioButton rb = (RadioButton) group.findViewById(checkedId);
//                tvAddressInfoAddress.setText(rb.getText().toString());
//
//                // 给服务器的地址簿ID
//                int indexPaymentList = group.indexOfChild(rb);
//                // 在集合中查找
//            }
//        });
//        rgAddressInfo.check(rgAddressInfo.getChildAt(0).getId());
}

        public void initAddressList(){
            View view = View.inflate(this, R.layout.item_addressinfo, null);
            ListView lvAddressList = (ListView) view.findViewById(R.id.lv_address_list);
            final List<String> data = initAddressListData();
            lvAddressList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));

            popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow.setBackgroundDrawable(new ColorDrawable());
            popupWindow.setFocusable(true);
            popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {

                }
            });

            lvAddressList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    tvAddressInfoAddress.setText(data.get(position));
                    mOrder.addressId = addressLists[position].getId();

                    popupWindow.dismiss();
                }
            });
        }

        private List<String> initAddressListData() {
            List<String> addressInfos=  new ArrayList<>();
            for (AddressInfo addressList : addressLists) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(addressList.getProvince())
                        .append(addressList.getCity())
                        .append(addressList.getAddressArea())
                        .append(addressList.getAddressDetail());
                addressInfos.add(stringBuilder.toString());
            }
            return addressInfos;
        }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }


    private void initProductList() {
        // TODO: 2016/4/23 填充从服务器获取的信息,增加子布局
//        View itemProductList = View.inflate(this, R.layout.item_productlist, null);
//        ImageView ivProductListPic = (ImageView) itemProductList.findViewById(R.id.iv_productList_pic);
//        TextView tvProductListName = (TextView) itemProductList.findViewById(R.id.tv_productList_name);
//        TextView tvProductListPrice = (TextView) itemProductList.findViewById(R.id.tv_productList_price);
//        TextView tvProductListProdNum = (TextView) itemProductList.findViewById(R.id.tv_productList_prodNum);

        List<ProductList> mProductList = checkoutResp.productList;
        if (mProductList==null){
            return;
        }
        for (ProductList item : mProductList) {
            View itemProductList = View.inflate(this, R.layout.item_productlist, null);
            ImageView ivProductListPic = (ImageView) itemProductList.findViewById(R.id.iv_productList_pic);
            TextView tvProductListName = (TextView) itemProductList.findViewById(R.id.tv_productList_name);
            TextView tvProductListPrice = (TextView) itemProductList.findViewById(R.id.tv_productList_price);
            TextView tvProductListProdNum = (TextView) itemProductList.findViewById(R.id.tv_productList_prodNum);

            String url = CommonConstant.HOST + item.product.pic;
            Glide.with(this).load(url).centerCrop().crossFade().into(ivProductListPic);
            tvProductListName.setText(item.product.name);
            Log.d("test",item.product.price+"");
            Log.d("test",tvProductListPrice==null?"null":"notNoll");
            tvProductListPrice.setText(item.product.price+"");
            tvProductListProdNum.setText("X "+item.prodNum);
            productList.addView(itemProductList);
        }


    }

    private void initCheckoutProm() {
        // TODO: 2016/4/23 填充从服务器获取的信息
        StringBuilder checkoutPromtest = new StringBuilder();
        for (String string : checkoutResp.checkoutProm) {
            checkoutPromtest.append(string + "\n");
        }
        tvCheckoutPromContent.setText(checkoutPromtest.substring(0, checkoutPromtest.length() - 1));

    }

    private void initCheckoutAddup() {
        // TODO: 2016/4/23 填充从服务器获取的信息
        tvCheckoutAddupTotalPoint.setText("商品积分总计:"+checkoutResp.checkoutAddup.totalPoint);
        tvCheckoutAddupTotalCount.setText("商品金额总计:"+checkoutResp.checkoutAddup.totalPrice);
        tvCheckoutAddupFreight.setText("包含运费"+checkoutResp.checkoutAddup.freight+"元");
        tvCheckoutAddupProdNum.setText("X "+checkoutResp.checkoutAddup.totalCount);
    }

    private void initInvoice() {
        rgInvoiceType.check(rgInvoiceType.getChildAt(0).getId());
        rgInvoiceTitle.check(rgInvoiceTitle.getChildAt(0).getId());
        rgInvoiceMaterial.check(rgInvoiceMaterial.getChildAt(0).getId());
        rgInvoiceContent.check(rgInvoiceContent.getChildAt(0).getId());
        etInvoiceTitle.setText("");
        tvInvoice.setText("发票信息: 普通发票(纸质发票) - 个人");

        invoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.RIGHT);
            }
        });
        mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // 设置界面数据
                RadioButton rbInvoiceType = (RadioButton) rgInvoiceType.findViewById(rgInvoiceType.getCheckedRadioButtonId());
                RadioButton rbInvoiceTitle = (RadioButton) rgInvoiceTitle.findViewById(rgInvoiceTitle.getCheckedRadioButtonId());
                RadioButton rbInvoiceMaterial = (RadioButton) rgInvoiceMaterial.findViewById(rgInvoiceMaterial.getCheckedRadioButtonId());
                RadioButton rbInvoiceContent = (RadioButton) rgInvoiceContent.findViewById(rgInvoiceContent.getCheckedRadioButtonId());
                String strInvoiceType = rbInvoiceType.getText().toString();
                String strInvoiceMaterial = rbInvoiceMaterial.getText().toString();
                String strInvoiceTitle = rbInvoiceTitle.getText().toString();
                String strInvoiceContent = rbInvoiceContent.getText().toString();
                tvInvoice.setText("发票信息: " + strInvoiceType + "(" + strInvoiceMaterial + ") - " + strInvoiceTitle);

                // 给服务器的发票数据
                int indexInvoiceType = rgInvoiceType.indexOfChild(rbInvoiceType);
                int indexInvoiceTitle = rgInvoiceTitle.indexOfChild(rbInvoiceTitle) ;
                int indexInvoiceMaterial = rgInvoiceMaterial.indexOfChild(rbInvoiceMaterial);
                int indexrgInvoiceContent = rgInvoiceContent.indexOfChild(rbInvoiceContent);
                String strInvoiceTitleContent = etInvoiceTitle.getText().toString().trim();

                mOrder.invoiceType = indexInvoiceType;
                mOrder.invoiceTitle = strInvoiceTitleContent;
                mOrder.invoiceContent = strInvoiceContent;

            }
        });


    }

    private void initDeliveryList() {
        deliveryList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deliveryListExpandLayout.toggle();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                }, 200);
            }
        });
        rgDeliveryList.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                tvDeliveryList.setText("送货时间：" + rb.getText().toString());

                // 给服务器的送货时间
                int indexDeliveryList = group.indexOfChild(rb);
                mOrder.deliveryType = indexDeliveryList;
            }
        });
        rgDeliveryList.check(rgDeliveryList.getChildAt(0).getId());
    }

    private void initPaymentList() {
        paymentList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paymentListExpandLayout.toggle();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                }, 200);
            }
        });
        rgPaymentList.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                tvPaymentList.setText("支付方式：" + rb.getText().toString());

                // 给服务器的支付方式
                int indexPaymentList = group.indexOfChild(rb);
                mOrder.paymentType = indexPaymentList;
            }
        });
        rgPaymentList.check(rgPaymentList.getChildAt(0).getId());
    }

    private void initView() {
        // 抽屉布局
        mScrollView = (ScrollView) findViewById(R.id.sv);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl);
        mDrawerLayoutRight = (LinearLayout) findViewById(R.id.dl_right);

        // 地址信息
        rlAddressInfo = (RelativeLayout) findViewById(R.id.addressInfo);
        tvAddressInfoName = (TextView) findViewById(R.id.tv_addressInfo_name);
        tvAddressPhoneNumber = (TextView) findViewById(R.id.tv_addressInfo_phoneNumber);
        ivAddressInfoAddress = (ImageView) findViewById(R.id.iv_addressInfo_address);
        tvAddressInfoAddress = (TextView) findViewById(R.id.tv_addressInfo_address);
//        addressInfoExpandLayout = (ExpandableRelativeLayout) findViewById(R.id.addressInfo_expandableLayout);
//        rgAddressInfo = (RadioGroup) findViewById(R.id.rg_addressInfo);

        // 商品信息
        productList = (LinearLayout) findViewById(R.id.productList);
        ivProductListPic = (ImageView) findViewById(R.id.iv_productList_pic);
        tvProductListName = (TextView) findViewById(R.id.tv_productList_name);
        tvProductListPrice = (TextView) findViewById(R.id.tv_productList_price);
        tvProductListProdNum = (TextView) findViewById(R.id.tv_productList_prodNum);

        // 促销信息
        checkoutProm = (LinearLayout) findViewById(R.id.checkoutProm);
        tvCheckoutPromContent = (TextView) findViewById(R.id.tv_checkoutProm_content);

        // 账目信息
        checkoutAddup = (RelativeLayout) findViewById(R.id.checkoutAddup);
        tvCheckoutAddupTotalPoint = (TextView) findViewById(R.id.tv_checkoutAddup_totalPoint);
        tvCheckoutAddupTotalCount = (TextView) findViewById(R.id.tv_checkoutAddup_totalCount);
        tvCheckoutAddupFreight = (TextView) findViewById(R.id.tv_checkoutAddup_freight);
        tvCheckoutAddupProdNum = (TextView) findViewById(R.id.tv_checkoutAddup_prodNum);

        // 发票
        invoice = (RelativeLayout) findViewById(R.id.invoice);
        tvInvoice = (TextView) findViewById(R.id.tv_invoice);
        rgInvoiceType = (RadioGroup) findViewById(R.id.rg_invoiceType);
        rgInvoiceTitle = (RadioGroup) findViewById(R.id.rg_invoiceTitle);
        rgInvoiceMaterial = (RadioGroup) findViewById(R.id.rg_invoiceMaterial);
        rgInvoiceContent = (RadioGroup) findViewById(R.id.rg_invoiceContent);
        etInvoiceTitle = (EditText) findViewById(R.id.et_invoiceTitle);

        // 送货时间
        deliveryList = (RelativeLayout) findViewById(R.id.deliveryList);
        tvDeliveryList = (TextView) findViewById(R.id.tv_deliveryList);
        deliveryListExpandLayout = (ExpandableRelativeLayout) findViewById(R.id.deliveryList_expandableLayout);
        rgDeliveryList = (RadioGroup) findViewById(R.id.rg_deliveryList);

        // 支付方式
        paymentList = (RelativeLayout) findViewById(R.id.paymentList);
        tvPaymentList = (TextView) findViewById(R.id.tv_paymentList);
        paymentListExpandLayout = (ExpandableRelativeLayout) findViewById(R.id.paymentList_expandableLayout);
        rgPaymentList = (RadioGroup) findViewById(R.id.rg_paymentList);


    }

    private void initData() {
        getAddressInfo();
        String requestParams = getIntent().getStringExtra(CommonConstant.CART_TO_BILL);
        //Log.d("test",requestParams);
        if(TextUtils.isEmpty(requestParams)){
            return;
        }

        // 添加sku
        mOrder.sku = requestParams;

        HttpUtils mHttpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        String userId = SPUtil.getString(this, SPConstant.USER_INFO_USER_ID);
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        if (TextUtils.isEmpty(userId)){

//            Intent intent = new Intent(this,LoginAndRegisterActivity.class);
//            startActivity(intent);
            CommonUtil.showSafeToast(this,"还未登录");
            return ;
        }
        params.addHeader("userid", userId);
        params.addBodyParameter("sku", requestParams);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST + "/checkout",
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String json = responseInfo.result;
                            Log.d("test3", json);
                            Gson gson = new Gson();
                            checkoutResp = gson.fromJson(json, CheckoutResp.class);
                            initAddressInfo();
                            initProductList();
                            initCheckoutProm();
                            initCheckoutAddup();
                            initInvoice();
                            initDeliveryList();
                            initPaymentList();


                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Log.d("test", "访问失败");
                    }
                });
    }

    /**
     * 标题栏
     */
    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("结算中心");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.icon_back);
    }

    /**
     * 标题栏菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pay_center_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_order_submit:
                // 跳转提交订单
                if (mOrder.paymentType == 0) {
                    showDialog("正在获取订单...");
//                    Intent intent = new Intent(this, SuccessPayActivity.class);
//                    // TODO: 2016/4/25 携带数据
//                    startActivity(intent);
                    getDataFromNet();
                } else if (mOrder.paymentType == 1) {
                    // TODO: 2016/4/25 支付宝
                    payByAli();
                } else if (mOrder.paymentType == 2) {
                // TODO: 2016/4/25 微信
                    payByWeiXin();
                }



            break;
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getDataFromNet() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.configTimeout(10000);
        httpUtils.configDefaultHttpCacheExpiry(0);
        RequestParams params = new RequestParams();
        String userId = SPUtil.getString(this, SPConstant.USER_INFO_USER_ID);
        if (TextUtils.isEmpty(userId)) {
            CommonUtil.showSingleToast(this,"请先登录");
            return;}
        params.addHeader("userid",userId);
        //    POST	/ordersumbit	需要先登录获取userid，在将userid添加到请求头，如果返回错误码1533需要重新登录
//    参数名称	描述	样例
//    sku	商品ID:数量:属性ID|商品ID:数量:属性ID	1:3:1,2,3,4|2:2:2,3
//    addressId	地址簿ID	139
//    paymentType	支付方式	1  -- 0到付 1支付宝 2微信
//    deliveryType	送货时间	1
//    invoiceType	发票类型	1=>个人 2=>单位  改 0普通发票, 1电子发票
//    invoiceTitle	发票抬头	传智慧播客教育科技有限公司
//    invoiceContent
        params.addBodyParameter("sku",mOrder.sku);
        params.addBodyParameter("addressId",mOrder.addressId+"");
        params.addBodyParameter("paymentType",mOrder.paymentType+"");
        params.addBodyParameter("deliveryType",mOrder.deliveryType+"");
        params.addBodyParameter("invoiceType",mOrder.invoiceType+"");
        params.addBodyParameter("invoiceTitle",mOrder.invoiceTitle);
        params.addBodyParameter("invoiceContent",mOrder.invoiceContent);

        httpUtils.send(HttpRequest.HttpMethod.POST,
                CommonConstant.HOST + "/ordersumbit", params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        Log.d("test2",statusCode+"");
                        if (statusCode==200){
                            String json = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                json = jsonObject.getString("orderInfo");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                            Intent intent =new Intent(PayCenterActivity.this,SuccessPayActivity.class);

                            intent.putExtra("mm",json);

                            hideDialog();
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Log.d("test2","点单访问失败");
                    }
                });
    }

    private void getAddressInfo(){
        HttpUtils mHttpUtils = new HttpUtils();
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();

        String userId = SPUtil.getString(this, SPConstant.USER_INFO_USER_ID);
        Log.d("test1",userId);
        if(TextUtils.isEmpty(userId)){
            return;
        }

       // params.addQueryStringParameter("userid",userId);
        params.addHeader("userid",userId);
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST + "/addresslist", params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                int statusCode = responseInfo.statusCode;
                Log.d("test1",statusCode+"");
                if (statusCode==1533){
                    CommonUtil.showSingleToast(PayCenterActivity.this,"请重新登录");
                    return;
                }
                if (statusCode==200){
                    String json = responseInfo.result;
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        Log.d("test1",json);
                        String addressList = jsonObject.getString("addressList");
                        Log.d("test1",addressList);
                        addressLists = new Gson().fromJson(addressList,AddressInfo[].class);

                        Log.d("test1",addressLists.toString());
                        initAddressList();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.d("test1","访问失败");
            }
        });
    }



    // 调用支付宝支付
    void payByAli() {
        showDialog("正在获取订单...");
        final String name = getName();

//        tv.append("正在获取订单...");
        // BmobPay.init(this, APPID);

        BP.pay(this, name, getBody(), getPrice(), true, new PListener() {

            // 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
            @Override
            public void unknow() {
                Toast.makeText(PayCenterActivity.this, "支付结果未知,请稍后手动查询",
                        Toast.LENGTH_SHORT).show();
//                tv.append(name + "'s pay status is unknow\n\n");
                hideDialog();
            }

            // 支付成功,如果金额较大请手动查询确认
            @Override
            public void succeed() {
                Toast.makeText(PayCenterActivity.this, "支付成功!", Toast.LENGTH_SHORT)
                        .show();
//                tv.append(name + "'s pay status is success\n\n");
                hideDialog();


            }

            // 无论成功与否,返回订单号
            @Override
            public void orderId(String orderId) {
                // 此处应该保存订单号,比如保存进数据库等,以便以后查询
//                order.setText(orderId);
//                tv.append(name + "'s orderid is " + orderId + "\n\n");
                showDialog("获取订单成功!请等待跳转到支付页面~");
            }

            // 支付失败,原因可能是用户中断支付操作,也可能是网络原因
            @Override
            public void fail(int code, String reason) {
                Toast.makeText(PayCenterActivity.this, "支付中断!", Toast.LENGTH_SHORT)
                        .show();
//                tv.append(name + "'s pay status is fail, error code is " + code
//                        + " ,reason is " + reason + "\n\n");
                hideDialog();
            }
        });
    }

    // 调用微信支付
    void payByWeiXin() {
        showDialog("正在获取订单...");
        final String name = getName();

        BP.pay(this, name, getBody(), getPrice(), false, new PListener() {

            // 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
            @Override
            public void unknow() {
                Toast.makeText(PayCenterActivity.this, "支付结果未知,请稍后手动查询",
                        Toast.LENGTH_SHORT).show();
//                tv.append(name + "'s pay status is unknow\n\n");
                hideDialog();
            }

            // 支付成功,如果金额较大请手动查询确认
            @Override
            public void succeed() {
                Toast.makeText(PayCenterActivity.this, "支付成功!", Toast.LENGTH_SHORT)
                        .show();
//                tv.append(name + "'s pay status is success\n\n");
                hideDialog();
            }

            // 无论成功与否,返回订单号
            @Override
            public void orderId(String orderId) {
                // 此处应该保存订单号,比如保存进数据库等,以便以后查询
//                order.setText(orderId);
//                tv.append(name + "'s orderid is " + orderId + "\n\n");
                showDialog("获取订单成功!请等待跳转到支付页面~");
            }

            // 支付失败,原因可能是用户中断支付操作,也可能是网络原因
            @Override
            public void fail(int code, String reason) {

                // 当code为-2,意味着用户中断了操作
                // code为-3意味着没有安装BmobPlugin插件
                if (code == -3) {
                    new AlertDialog.Builder(PayCenterActivity.this)
                            .setMessage(
                                    "监测到你尚未安装支付插件,无法进行微信支付,请选择安装插件(已打包在本地,无流量消耗)还是用支付宝支付")
                            .setPositiveButton("安装",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            installBmobPayPlugin("bp_wx.db");
                                        }
                                    })
                            .setNegativeButton("支付宝支付",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            payByAli();
                                        }
                                    }).create().show();
                } else {
                    Toast.makeText(PayCenterActivity.this, "支付中断!",
                            Toast.LENGTH_SHORT).show();
                }
//                tv.append(name + "'s pay status is fail, error code is " + code
//                        + " ,reason is " + reason + "\n\n");
                hideDialog();
            }
        });
    }

    // 默认为0.02
    double getPrice() {
        double price = 0.02;
//        try {
//            price = Double.parseDouble(this.price.getText().toString());
//        } catch (NumberFormatException e) {
//        }
        return price;
    }

    // 商品详情(可不填)
//    String getName() {
//        return this.name.getText().toString();
//    }
    String getName() {
        return "商品名";
    }

    // 商品详情(可不填)
//    String getBody() {
//        return this.body.getText().toString();
//    }
    String getBody() {
        return "商品描述";
    }

    // 支付订单号(查询时必填)
//    String getOrder() {
//        return this.order.getText().toString();
//    }

    void showDialog(String message) {
        try {
            if (dialog == null) {
                dialog = new ProgressDialog(this);
                dialog.setCancelable(true);
            }
            dialog.setMessage(message);
            dialog.show();
        } catch (Exception e) {
            // 在其他线程调用dialog会报错
        }
    }

    void hideDialog() {
        if (dialog != null && dialog.isShowing())
            try {
                dialog.dismiss();
            } catch (Exception e) {
            }
    }

    void installBmobPayPlugin(String fileName) {
        try {
            InputStream is = getAssets().open(fileName);
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + fileName + ".apk");
            if (file.exists())
                file.delete();
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file://" + file),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
